package comp.config.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import comp.config.entity.Config;
import comp.config.repository.ConfigRepository;

@Service
public class ConfigService {

	public static final String DEFAULT = "default";

	public static final String DEFAULT_MP = "default";

	public static final String DEFAULT_OPEN = "default_open";

	public static final String OPEN = "open";

	public static final String MP = "mp";

	public static final String CP = "cp";

	public static final String MINIAPP = "miniapp";

	@Autowired
	private ConfigRepository configRepository;

	public Config getConfig(String id) {
		return configRepository.findOne(id);
	}

	public List<Config> findAll() {

		return configRepository.findAll();
	}

	/**
	 * 隐藏敏感配置信息，替换为***
	 * 
	 * @param configs
	 * @return
	 */
	private List<Config> hideSecureInfo(Config... configs) {
		for (Config config : configs) {
			if (config.getIssecure() == 1) {
				config.setFvalue("***");
			}
		}
		return Arrays.asList(configs);
	}

	public List<Config> addConfig(List<Config> configs) throws RuntimeException {
		// Config config = configs.get(0);
		// String group = config.getFgroup();
		// List<Config> configs2 = configRepository.queryEntityByFgroupEquals(group);
		// if(configs2 != null && !configs2.isEmpty()) {
		// for (Config c1 : configs) {
		// for (Config c2 : configs2) {
		// if(c1.getFkey().equals(c2.getFkey())) {
		// c1.setId(c2.getId());
		// break;
		// }
		// }
		// }
		// }
		Config config = configs.get(0);
		String id = config.getId();
		if (StringUtils.isEmpty(id)) {// 新增保存数据
			String group = config.getFgroup();
			List<Config> configs2 = configRepository.queryEntityByFgroupEquals(group);
			if (configs2 != null && !configs2.isEmpty()) {
				throw new RuntimeException("分组fgroup已经存在！");
			}
		}
		//去空格
		trimConfig(configs);
		return configRepository.save(configs);
	}

	public void removeById(String id) {
		Config config = configRepository.findOne(id);
		if (config != null) {
			configRepository.delete(config);
		}
	}

	public List<Config> getConfigsByKey(String key, String group, String credential) {
		if (StringUtils.isEmpty(group) && (key.contains(MP) || key.contains(OPEN) || key.contains(CP))) {
			switch (key) {
			case MP:
				group = DEFAULT_MP;
				break;
			case OPEN:
				group = DEFAULT_OPEN;
				break;
			default:
				group = DEFAULT;
				break;
			}
		} else {// 小程序
			if (StringUtils.isEmpty(group)) {
				List<Config> configs = configRepository.queryEntityByFkeyEquals(key);
				if (configs == null || configs.isEmpty()) {
					configs = configRepository.queryEntityByFkeyLike(key+"%");
				}
				if (StringUtils.isEmpty(credential) && configs != null && !configs.isEmpty()) {
					return hideSecureInfo(configs.stream().toArray(size -> new Config[size]));
				}
				return configs;
			}
		}
		// 优先key equals查询
		List<Config> configs = configRepository.queryEntityByFkeyEqualsAndFgroupEquals(key, group);
		// 检索不到后再进行key like查询
		if (configs == null || configs.isEmpty()) {
			configs = configRepository.queryEntityByFkeyLikeAndFgroupEquals(key + "%", group);
		}
		if (StringUtils.isEmpty(credential) && configs != null && !configs.isEmpty()) {
			return hideSecureInfo(configs.stream().toArray(size -> new Config[size]));
		}
		return configs;
	}

	public List<Config> getConfigsByAppid(String appid, String credential) {
		Config config = configRepository.queryTopEntityByFvalueEqualsAndFkeyEquals(appid,
				"com.qq.weixin.miniapp.appID");
		if (config == null) {

			return Collections.emptyList();
		}
		List<Config> configs = configRepository.queryEntityByFgroupEquals(config.getFgroup());
		if (StringUtils.isEmpty(credential)) {
			return hideSecureInfo(configs.stream().toArray(size -> new Config[size]));
		}
		return configs;
	}

	public Config appendValue(String id, JSONObject value) {
		Config config = configRepository.findOne(id);
		return appendValue(config, value);
	}

	private Config appendValue(Config config, JSONObject value) {
		// 为空append配置
		if (StringUtils.isEmpty(config.getFvalue())) {
			List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
			jsonObjects.add(value);
			config.setFvalue(JSONObject.toJSONString(jsonObjects));
		} else {// 不为空则判断有误当前valueId对应的配置，没有则append，有则update
			List<JSONObject> jsonArray = JSONObject.parseArray(config.getFvalue(), JSONObject.class);
			List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
			for (JSONObject json : jsonArray) {
				if (!json.getString("id").equals(value.getString("id"))) {
					jsonObjects.add(json);
				}
			}
			jsonObjects.add(value);
			config.setFvalue(JSONObject.toJSONString(jsonObjects));
		}
		return configRepository.save(config);
	}

	public Config removeValue(String id, String valueId) {
		Config config = configRepository.findOne(id);
		return removeValue(config, valueId);
	}

	private Config removeValue(Config config, String valueId) {
		if (config != null) {
			List<JSONObject> jsonArray = JSONObject.parseArray(config.getFvalue(), JSONObject.class);
			List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
			for (JSONObject json : jsonArray) {
				if (!json.getString("id").equals(valueId)) {
					jsonObjects.add(json);
				}
			}
			config.setFvalue(JSONObject.toJSONString(jsonObjects));
		}
		return configRepository.save(config);

	}

	public Config getConfigByKey(String key, String group, String credential) {
		Config config = new Config();
		if (StringUtils.isEmpty(group) && (key.contains(MP) || key.contains(OPEN) || key.contains(CP))) {
			switch (key) {
			case MP:
				group = DEFAULT_MP;
				break;
			case OPEN:
				group = DEFAULT_OPEN;
				break;
			default:
				group = DEFAULT;
				break;
			}
		} else {
			if (StringUtils.isEmpty(group)) {
				List<Config> configs = configRepository.queryEntityByFkeyEquals(key);
				if (configs != null && !configs.isEmpty()) {
					config = configs.get(0);
					if (StringUtils.isEmpty(credential)) {
						config = hideSecureInfo(config).get(0);
					}
					return config;
				}
			}

		}
		List<Config> configs = configRepository.queryEntityByFkeyEqualsAndFgroupEquals(key, group);
		if (configs != null && !configs.isEmpty()) {
			config = configs.get(0);
			if (StringUtils.isEmpty(credential)) {
				config = hideSecureInfo(config).get(0);
			}
		}
		return config;
	}

	public Config appendItem(String key, JSONObject jsonObject) {
		List<Config> configs = configRepository.queryEntityByFkeyEquals(key);
		if (configs != null && !configs.isEmpty()) {

			return appendValue(configs.get(0), jsonObject);
		}
		return null;
	}

	public Config removeItem(String key, String valueId) {
		List<Config> configs = configRepository.queryEntityByFkeyEquals(key);
		if (configs != null && !configs.isEmpty()) {

			return removeValue(configs.get(0), valueId);
		}
		return null;
	}

	public List<Config> getConfigsByKey(String key) {

		return configRepository.queryEntityByFkeyEquals(key);
	}

	public void removeByGroup(String group) {
		List<Config> configs = configRepository.queryEntityByFgroupEquals(group);
		if (configs != null && !configs.isEmpty()) {
			configRepository.delete(configs);
		}
	}
	
	public void trimConfig(List<Config> configs) {
		if(configs == null || configs.isEmpty()) {
			return;
		}
		for (Config config : configs) {
			if(StringUtils.isNotEmpty(config.getId())) {
				config.setId(config.getId().trim());
			}
			if(StringUtils.isNotEmpty(config.getFkey())) {
				config.setFkey(config.getFkey().trim());
			}
			if(StringUtils.isNotEmpty(config.getFlabel())) {
				config.setFlabel(config.getFlabel().trim());
			}
			if(StringUtils.isNotEmpty(config.getFvalue())) {
				config.setFvalue(config.getFvalue().trim());
			}
		}
	}
}
